
--[[
	**********************
	* SvFrame - thomasfn *
	**********************
	commands.lua - Loads commands framework
]]

local Commands = {}

function svr.AddCommand( name, func, validator )

	if (Commands[ name ]) then
		return svr.Warning( "Command '" .. name .. "' already exists!" )
	end

	local t = type( func )

	if (t == "function") then
		Commands[ name ] = func
		--svr.Print( "Added command '" .. name .. "'." )
	elseif (t == "table") then

		local function ERR( ply )
			if (func.help) then
				func.help( ply, {} )
				return
			end
			local tmp = {}
			for key, val in pairs( func ) do
				tmp[ #tmp + 1 ] = key
			end
			ply:ChatPrint( colour.White, "Valid subcommands of '", colour.DarkTeal, name, colour.White, "' are: ", table.concat( tmp, ", " ) )
		end
		
		local function CMD( ply, args )
			if (#args == 0) then
				ERR( ply )
				return
			end
			if (validator and (not validator( ply ))) then return end
			local c = args[1]:lower()
			table.remove( args, 1 )
			if (not func[ c ]) then
				ERR( ply )
				return
			end
			local b, res = pcall( func[ c ], ply, args )
			if (not b) then
				ply:ChatPrint( colour.Red, "Uh oh! Please report this message." )
				ply:ChatPrint( colour.Red, name .. "/" .. c .. ": " .. res )
			end
		end
		Commands[ name ] = CMD
		--svr.Print( "Added command '" .. name .. "' (with subcommands)." )
	end
end

function svr.RemoveCommand( name )
	Commands[ name ] = nil
end

function svr.AliasCommand( orig, new )
	Commands[ new ] = Commands[ orig ]
end

local function CmdHandler( ply, com, args )
	if (not ply) then return end
	if (com == "") then return end
	
	local cmd = Commands[ com:lower() ]
	if (not cmd) then
		ply:ChatPrint( colour.Red, "Command '", colour.DarkTeal, com, colour.Red, "' wasn't recognised!" )
		return false
	end
	
	--table.remove( args, 1 )
	
	local b, res = pcall( cmd, ply, args )
	if (not b) then
		ply:ChatPrint( colour.Red, "Uh oh! Please report this message." )
		ply:ChatPrint( colour.Red, com .. ": " .. res )
	end
	
	return false
end
hooks.Add( "player.command", "SvFrame_Command", CmdHandler )

svr.AddCommand( "commands", function( ply, args )
	local tmp = {}
	local tmp2 = {}
	for name, _ in pairs( Commands ) do
		tmp2[ #tmp2 + 1 ] = colour.Teal .. "^" .. name .. colour.White .. "^"
		if (#tmp2 == 8) then
			tmp[ #tmp + 1 ] = tmp2
			tmp2 = {}
		end
	end
	if (#tmp2 > 0) then tmp[ #tmp + 1 ] = tmp2 end
	ply:ChatPrint(  "Valid commands are: " .. table.concat( tmp[1], ", " ) .. (((#tmp > 1) and ",") or "") )
	for i=2, #tmp do
		ply:ChatPrint(  table.concat( tmp[i], ", " ) .. (((#tmp > i) and ",") or "") )
	end
end )
svr.AliasCommand( "commands", "help" )